import c from '../colors';
import { runTask } from '../common';
import type { Config } from '../definitions';
import { logSuccess } from '../log';
import type { BuildCommandOptions } from '../tasks/build';
import { runCommand } from '../util/subprocess';

export async function buildOhos(config: Config, buildOptions: BuildCommandOptions): Promise<void> {
  const buildArgs = ['build'];
  
  if (buildOptions.configuration) {
    buildArgs.push('--configuration', buildOptions.configuration);
  }

  try {
    await runTask('Running HarmonyOS build', async () =>
      runCommand('hvigor', buildArgs, {
        cwd: config.ohos.platformDirAbs,
      }),
    );
    
    logSuccess('HarmonyOS build completed successfully!');
  } catch (e) {
    if ((e as any).includes('ENOENT')) {
      throw `hvigor command not found. Please ensure HarmonyOS SDK is properly installed and hvigor is in your PATH. ${c.strong(
        'Download DevEco Studio: https://developer.harmonyos.com/cn/develop/deveco-studio'
      )}`;
    } else {
      throw new Error(`HarmonyOS build failed: ${e}`);
    }
  }
}